const express = require('express');
const router = express.Router();
const ListsModel = require('../db/modules/lists');
const dayjs = require('dayjs')
const checkLogin = require('../middleWares/checkLogin')

router.get('/', checkLogin, function(req, res, next) {
  res.redirect('/list')
});

router.get('/list', checkLogin, function(req, res, next) {
  ListsModel.find({}).sort({time:-1}).then((result) => {
    // console.log('获取成功',result);
    res.render('index',{list:result,dayjs})
  }).catch((error) => {
    console.log('获取错误',error);
    res.status(500).send(error)
  })
});

router.get('/create-list', checkLogin, function(req, res, next) {
  res.render('create')
});

// 增
router.post('/list-create', checkLogin, function(req, res, next) {
  ListsModel.create({
    ...req.body,
    time:dayjs(req.body.time).format('YYYY-MM-DD')
  }).then((result) => {
    console.log('创建成功',result);
    res.render('success',{tips:'添加成功啦',url:'/list'})
  }).catch((error) => {
    console.log('创建错误',error);
    res.status(500).send(error)
  })
})
// 删
router.get('/list-delete/:id', checkLogin, function(req, res, next) {
  const _id = req.params.id
  ListsModel.deleteOne({_id}).then((result) => {
    console.log('删除成功',result);
    res.render('success',{tips:'删除成功啦',url:'/list'})
  }).catch((error) => {
    console.log('删除错误',error);
    res.status(500).send(error)
  })
})

module.exports = router;
